<template>
  <div class="kcjxzj-summary-audit">
    <div class="page-header">
      <h1>审核课程教学总结</h1>
      <div class="actions">
        <el-button @click="router.go(-1)">
          <el-icon><Back /></el-icon> 返回
        </el-button>
      </div>
    </div>
    
    <el-card v-loading="loading" class="summary-card">
      <template #header>
        <div class="card-header">
          <span>总结基本信息</span>
        </div>
      </template>
      
      <div v-if="summary" class="summary-info">
        <!-- 使用与编辑页面相同的基本信息组件，但设为只读模式 -->
        <SummaryBasicInfo
          :model-value="summaryFormData"
          :courses="courses"
          :terms="terms"
          :departments="departments"
          :teaching-missions="teachingMissions"
          :is-readonly="true"
          :current-mission-id="null"
        />
        
        <!-- 其他详细信息 -->
        <el-descriptions :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="提交时间">
            <el-tag size="small" type="success" effect="plain">{{ formatDate(summary.commitDate) }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 成绩统计信息 -->
        <div v-if="summary.teachingMissionIds && summary.teachingMissionIds.length > 0" class="score-statistics-section">
          <ScoreStatistics :teaching-mission-ids="summary.teachingMissionIds" />
        </div>
        
        <!-- 重复度检测 -->
        <div class="duplication-check-section">
          <DuplicationCheck :summary-id="summary.id" />
        </div>
        
        <!-- 总结内容 -->
        <div class="summary-content">
          <h3>总结内容</h3>
          
          <div class="content-section">
            <h4>考试考核</h4>
            <div class="content-box">
              <RichTextViewer :content="summary.assessment || '未填写'" />
            </div>
          </div>
          
          <div class="content-section">
            <h4>教学设计与实施</h4>
            <div class="content-box">
              <RichTextViewer :content="summary.designAndImplementation || '未填写'" />
            </div>
          </div>
          
          <div class="content-section">
            <h4>教学反思与改进</h4>
            <div class="content-box">
              <RichTextViewer :content="summary.reflectionAndImprovement || '未填写'" />
            </div>
          </div>
        </div>
      </div>
      
      <div v-else-if="!loading" class="empty-data">
        <el-empty description="未找到相关总结信息"></el-empty>
      </div>
    </el-card>
    
    <el-card v-if="summary" class="audit-card">
      <template #header>
        <div class="card-header">
          <span>审核意见</span>
        </div>
      </template>
      
      <el-form :model="auditForm" label-width="120px">
        <el-form-item label="审核意见">
          <el-input 
            type="textarea" 
            v-model="auditForm.comments" 
            placeholder="请输入审核意见" 
            :rows="4"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="approve">
            <el-icon><Check /></el-icon> 通过
          </el-button>
          <el-button type="danger" @click="reject">
            <el-icon><Close /></el-icon> 驳回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getKcjxzjById, auditByResearch, auditByDepartment } from '@/api/course-teaching-summary';
import { departmentApi, courseApi, termApi } from '@/api/base-data';
import { teachingMissionApi } from '@/api/teaching-mission';
import { useUserStore } from '@/stores/user';
import { Check, Close, Back } from '@element-plus/icons-vue';
import ScoreStatistics from '@/components/summary/ScoreStatistics.vue';
import DuplicationCheck from '@/components/common/DuplicationCheck.vue';
import RichTextViewer from '@/components/common/RichTextViewer.vue';
import SummaryBasicInfo from '@/components/summary/SummaryBasicInfo.vue';

export default {
  components: {
    Check,
    Close,
    Back,
    ScoreStatistics,
    DuplicationCheck,
    RichTextViewer,
    SummaryBasicInfo
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const userStore = useUserStore();
    const summary = ref(null);
    const loading = ref(true);
    const courses = ref([]);
    const terms = ref([]);
    const departments = ref([]);
    const teachingMissions = ref([]);
    const auditForm = ref({
      comments: '',
      approved: false
    });

    // 将总结数据转换为表单数据格式，供 SummaryBasicInfo 组件使用
    const summaryFormData = computed(() => {
      if (!summary.value) {
        return {
          courseId: null,
          termId: null,
          departmentIds: [],
          textbook: '',
          textbookType: '',
          teachingMissionIds: []
        };
      }
      
      return {
        courseId: summary.value.courseId,
        termId: summary.value.termId,
        departmentIds: summary.value.departmentIds || [],
        textbook: summary.value.textbook || '',
        textbookType: summary.value.textbookType || '',
        teachingMissionIds: summary.value.teachingMissionIds || []
      };
    });

    // 加载基础数据
    const loadBaseData = async () => {
      try {
        const [coursesData, termsData, missionsData, departmentsData] = await Promise.all([
          courseApi.getAllCourses(),
          termApi.getAllTerms(),
          teachingMissionApi.getAllTeachingMissionsList(),
          departmentApi.getAllDepartments()
        ]);
        
        courses.value = coursesData || [];
        terms.value = termsData || [];
        teachingMissions.value = Array.isArray(missionsData) ? missionsData : (missionsData?.content || missionsData?.data || []);
        departments.value = departmentsData || [];
      } catch (error) {
        console.error('获取基础数据失败:', error);
      }
    };

    const fetchSummary = async () => {
      loading.value = true;
      try {
        const id = route.params.id;
        summary.value = await getKcjxzjById(id);
      } catch (error) {
        ElMessage.error('获取总结详情失败');
      } finally {
        loading.value = false;
      }
    };

    const formatDate = (dateString) => {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };

    const approve = async () => {
      if (!auditForm.value.comments.trim()) {
        ElMessage.warning('请填写审核意见');
        return;
      }
      
      try {
        await ElMessageBox.confirm('确定要通过此教学总结吗？', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        });
        
        if (userStore.isResearchHead) {
          await auditByResearch(route.params.id, { ...auditForm.value, approved: true });
        } else if (userStore.isDepartmentHead) {
          await auditByDepartment(route.params.id, { ...auditForm.value, approved: true });
        }
        ElMessage.success('审核通过成功');
        router.push('/kcjxzj/summary-audit-list');
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('审核失败');
        }
      }
    };

    const reject = async () => {
      if (!auditForm.value.comments.trim()) {
        ElMessage.warning('请填写驳回原因');
        return;
      }
      
      try {
        await ElMessageBox.confirm('确定要驳回此教学总结吗？', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        if (userStore.isResearchHead) {
          await auditByResearch(route.params.id, { ...auditForm.value, approved: false });
        } else if (userStore.isDepartmentHead) {
          await auditByDepartment(route.params.id, { ...auditForm.value, approved: false });
        }
        ElMessage.success('驳回成功');
        router.push('/kcjxzj/summary-audit-list');
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('审核失败');
        }
      }
    };

    onMounted(async () => {
      await Promise.all([
        loadBaseData(),
        fetchSummary()
      ]);
    });

    return {
      summary,
      loading,
      courses,
      terms,
      departments,
      teachingMissions,
      summaryFormData,
      auditForm,
      approve,
      reject,
      formatDate,
      router
    };
  }
};
</script>

<style scoped>
.kcjxzj-summary-audit {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  margin-left: auto;
}

.summary-card,
.audit-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
}

.summary-info {
  margin-bottom: 20px;
}

.summary-content {
  margin-top: 20px;
}

.score-statistics-section {
  margin-top: 20px;
  margin-bottom: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
  min-height: 400px; /* 确保有足够的高度供图表渲染 */
}

.duplication-check-section {
  margin-top: 20px;
  margin-bottom: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.summary-content h3 {
  font-size: 16px;
  margin-bottom: 20px;
  font-weight: 600;
  color: #303133;
}

.content-section {
  margin-bottom: 30px;
}

.content-section h4 {
  font-size: 14px;
  margin-bottom: 10px;
  font-weight: 600;
  color: #409eff;
  border-left: 3px solid #409eff;
  padding-left: 10px;
}

.content-box {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  min-height: 100px;
  line-height: 1.6;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}
</style>
